<template>
  <div>
    <div class="inline-container">
      <!-- 新增角色 -->
      <el-button type="primary" icon="el-icon-plus" @click="addUserBox"
        >新增
      </el-button>
      <!-- 搜索框 -->
      <div class="centered-search">
        <el-form :inline="true" :model="sysUserQuery" class="demo-form-inline">
          <el-form-item label="用户账号">
            <el-input
              v-model="sysUserQuery.username"
              placeholder="用户账号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getUserData()">查询</el-button>
            <el-button @click="resetForm()">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 2、分隔线区域 -->
    <el-divider></el-divider>
    <!-- 3、表单 -->
    <el-table :data="userData" style="width: 100%" border>
      <el-table-column type="index" width="80" label="序号"></el-table-column>
      <el-table-column prop="headPic" label="头像" width="150">
        <template slot-scope="scope">
          <el-avatar
            v-if="scope.row.headPic"
            :src="scope.row.headPic"
          ></el-avatar>
          <el-avatar v-else icon="el-icon-user-solid"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="账号/用户名" width="150">
      </el-table-column>
      <el-table-column prop="fullName" label="姓名" width="150">
        <template slot-scope="scope">
          {{ scope.row.fullName || "-" }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="150">
        <template slot-scope="scope">
          {{ scope.row.phone || "-" }}
        </template>
      </el-table-column>
      <el-table-column prop="gender" label="性别" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.gender === 0">未知</el-tag>
          <el-tag v-else-if="scope.row.gender === 1">男</el-tag>
          <el-tag v-else>女</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="disable" label="用户状态" width="150">
        <template slot-scope="scope">
          <el-switch
            @change="disableChange(scope.row)"
            v-model="scope.row.disable"
            :active-value="0"
            :inactive-value="1"
            active-text="启用"
            inactive-text="禁用"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="regTime" label="注册时间" width="200">
      </el-table-column>
      <el-table-column prop="endTime" label="最后登录时间" width="200">
        <template slot-scope="scope">
          {{ scope.row.endTime || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="updUserInfoBox(scope.row)"
            title="修改"
          />
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteUser(scope.row.id)"
            title="删除"
            v-if="!scope.row.childrens"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="sysUserQuery.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="sysUserQuery.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!--form弹框  -->
    <!-- 弹框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      class="dialog"
    >
      <el-form :model="form" :rules="rules" ref="form" :inline="true">
        <el-form-item
          label="账号/用户名"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input size="small" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item
          label="姓名"
          prop="fullName"
          :label-width="formLabelWidth"
        >
          <el-input size="small" v-model="form.fullName"></el-input>
        </el-form-item>
        <el-form-item
          label="电话号码"
          prop="phone"
          :label-width="formLabelWidth"
        >
          <el-input size="small" v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age" :label-width="formLabelWidth">
          <el-input size="small" v-model="form.age"></el-input>
        </el-form-item>
        <el-form-item
          label="性别"
          prop="gender"
          style="width: 420px"
          :label-width="formLabelWidth"
        >
          <el-radio v-model="form.gender" :label="1">男</el-radio>
          <el-radio v-model="form.gender" :label="2">女</el-radio>
        </el-form-item>
        <el-form-item label="地址" prop="address" :label-width="formLabelWidth">
          <el-input size="small" v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="headPic" :label-width="formLabelWidth">
          <Upload
            :imageUrl="form.headPic"
            @upload-success="handleUploadSuccess"
          ></Upload>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            v-model="form.remarks"
            autocomplete="off"
            :rows="4"
            :autosize="{ minRows: 4, maxRows: 8 }"
            style="width: 500px"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="状态"
          prop="disable"
          :label-width="formLabelWidth"
          class="line"
        >
          <el-switch
            v-model="form.disable"
            :active-value="0"
            :inactive-value="1"
            active-text="启用"
            inactive-text="禁用"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="角色" prop="roleId" :label-width="formLabelWidth">
          <template>
            <el-radio-group v-model="form.roleId">
              <el-radio v-for="i in roleData" :label="i.id" :key="i.id">{{
                i.name
              }}</el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button type="primary" @click="addOrUpd()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, add, findById, upd, del, updDisable } from "@/services/user";
import { allList } from "@/services/role";
import Upload from "@/components/upload.vue";
export default {
  name: "user",
  components: {
    Upload,
  },
  data() {
    return {
      total: 0,
      formLabelWidth: "120px",
      dialogTitle: "",
      dialogVisible: false,
      sysUserQuery: {
        username: "",
        current: 1,
        size: 10,
      },
      userData: [],
      roleData: [],
      form: {
        username: "",
        phone: "",
        gender: 1,
        headPic: "",
        fullName: "",
        address: "",
        age: "",
        remarks: "",
        roleId: "",
        disable: 0,
        handleType: "ADD",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10个字符", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "电话号码不能为空", trigger: "blur" },
          {
            pattern: /^1(3|4|5|7|8)\d{9}$/, // 使用正则表达式校验手机号码，这里示例校验中国大陆手机号码
            message: "电话号码格式不正确",
            trigger: "blur",
          },
        ],
        roleId: [{ required: true, message: "角色不能为空", trigger: "blur" }],
      },
    };
  },

  mounted() {
    this.getUserData();
    this.getRoleList();
  },

  methods: {
    // -----------------crud---------------------------
    //获取角色列表
    async getRoleList() {
      allList()
        .then((res) => {
          this.roleData = res.data;
        })
        .catch((error) => {});
    },
    //用户列表
    getUserData() {
      list(this.sysUserQuery)
        .then((res) => {
          this.userData = res.data.records;
          this.total = res.data.total;
        })
        .catch((error) => {});
    },

    // 新增或者修改
    addOrUpd() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          //新增
          if (this.form.handleType === "ADD") {
            add(this.form)
              .then((res) => {
                this.$message({
                  type: "success",
                  message: "新增成功",
                });
                this.dialogVisible = false;
                this.getUserData();
              })
              .catch((error) => {});
          } else {
            //修改
            upd(this.form)
              .then((res) => {
                this.$message({
                  type: "success",
                  message: "修改成功",
                });
                this.dialogVisible = false;
                this.getUserData();
              })
              .catch((error) => {});
          }
        } else {
          return false;
        }
      });
    },
    // 启用禁用
    disableChange(userInfo) {
      updDisable(userInfo.id, userInfo.disable)
        .then((res) => {
          if (res.data) {
            this.getUserData();
            this.$message({
              type: "success",
              message: "修改成功",
            });
          }
        })
        .catch((error) => {});
    },
    //删除
    deleteUser(id) {
      this.$confirm("是否要删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          del(id)
            .then((res) => {
              if (res.data) {
                this.$message({
                  type: "success",
                  message: "删除成功",
                });
                this.dialogVisible = false;
                this.getUserData();
              }
            })
            .catch((error) => {});
          // this.submitRuleBaseSwitch(row, val); 调用接口修改数据
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消！",
          });
        });
    },
    //------------------其他---------------------------
    //头像上传成功
    handleUploadSuccess(imageUrl) {
      this.form.headPic = imageUrl;
    },
    //新增用户弹框
    addUserBox() {
      this.clearFrom();
      this.dialogTitle = "新增用户";
      this.dialogVisible = true;
    },
    //修改用户弹框
    updUserInfoBox(userInfo) {
      this.clearFrom();
      this.dialogTitle = "修改用户信息";
      this.dialogVisible = true;
      this.form.handleType = "UPD";
      findById(userInfo.id)
        .then((res) => {
          this.form.id = res.data.id;
          this.form.username = res.data.username;
          this.form.fullName = res.data.fullName;
          this.form.age = res.data.age;
          this.form.gender = res.data.gender;
          this.form.phone = res.data.phone;
          this.form.address = res.data.address;
          this.form.headPic = res.data.headPic;
          this.form.remarks = res.data.remarks;
          this.form.roleId = res.data.roleId;
        })
        .catch((error) => {});
    },
    // 重置搜索框
    resetForm() {
      this.sysUserQuery = {
        name: "",
        current: 1,
        size: 10,
      };
      this.getUserData();
    },
    //分页处理
    handleSizeChange(val) {
      this.sysUserQuery.size = val;
      this.getUserData();
    },
    handleCurrentChange(val) {
      this.sysUserQuery.current = val;
      this.getUserData();
    },
    //关闭弹框
    close() {
      this.dialogVisible = false;
      this.clearFrom();
    },
    clearFrom() {
      this.form = {
        username: "",
        phone: "",
        gender: 1,
        headPic: "",
        fullName: "",
        address: "",
        age: "",
        remarks: "",
        roleId: "",
        disable: 0,
        handleType: "ADD",
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.inline-container {
  height: 40px;
  display: flex;
  align-items: center; /* Optional: Align items vertically center if needed */
  .centered-search {
    margin-left: 30%;
    justify-content: center;
    margin-top: 26px;
  }
}
.page {
  display: flex;
  justify-content: flex-end;
}
.dialog {
  .el-input {
    width: 300px;
  }
  .line {
    width: 100%;
  }
}
</style>